//
//  ByCellOrderDetailAddPhoto.m
//  itboye_shop_ios
//
//  Created by mc on 17/2/17.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByCellOrderDetailAddPhoto.h"
@interface ByCellOrderDetailAddPhoto()
@property (nonatomic, strong) UICollectionView *collectionView;    // 图片视图
@end
@implementation ByCellOrderDetailAddPhoto

+ (instancetype)cellWithTableView:(UITableView*)tableView{
    
    static NSString *cellIdentifier = @"ByCellOrderDetailAddPhoto";
    ByCellOrderDetailAddPhoto *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[self alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    return cell;
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSeparatorStyleNone;
        [self _initViews];
    }
    return self;
}
#pragma mark -- 创建视图 --
- (void)_initViews {
    _imgAry = [[NSMutableArray alloc] init];
    // 图片选择
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = (SCREEN_WIDTH - 20 - 10)/3;
    CGFloat height = width;
    layout.itemSize = CGSizeMake(width, height);
    layout.minimumInteritemSpacing = 5;
    layout.minimumLineSpacing = 5;
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height) collectionViewLayout:layout];
    [self addSubview:_collectionView];
    // 设置代理和数据源方法
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.showsHorizontalScrollIndicator = NO;
    // 给集合视图注册一个类型的cell
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"ButtonCell"];
    
}

#pragma mark - collectionView 代理
// 定义展示的UICollectionViewCell的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
// 定义展示的Section的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imgAry.count + 1;
}
// 每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 按钮
    if (indexPath.row == _imgAry.count) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ButtonCell" forIndexPath:indexPath];
        UIImageView *addView = [[UIImageView alloc] init];
        [cell addSubview:addView];
        CGFloat width = (SCREEN_WIDTH - 20 - 10)/3;
        CGFloat height = width;
        addView.frame = CGRectMake(0, 10, width, height);
        
        addView.image = [UIImage imageNamed:@"添加图片按钮"];
        addView.backgroundColor = BY_THEME_COLOR;
        cell.layer.borderColor = ([UIColor colorWithRGBHex:0xd9d9d9]).CGColor;
        return cell;
        
    } else {
        
        id item = _imgAry[indexPath.row];
        UIImage *image = nil;
        if ([item isKindOfClass:[ALAsset class]]) {
            ALAsset *asset  = _imgAry[indexPath.row];
            image = [UIImage imageWithCGImage: asset.thumbnail];
        } else {
            image = (UIImage *)item;
        }
        
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
        //删除cell的所有子视图
        while ([cell.subviews lastObject] != nil)
        {
            [(UIView*)[cell.subviews lastObject] removeFromSuperview];
        }
        UIImageView *addView = [[UIImageView alloc] init];
        [cell addSubview:addView];
        CGFloat width = (SCREEN_WIDTH - 20 - 10)/3;
        CGFloat height = width;
        addView.frame = CGRectMake(0, 10, width, height);
        addView.image = image;
        addView.userInteractionEnabled = YES;
        
        // 删除按钮
        UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [cell addSubview:deleteBtn];
        deleteBtn.frame = CGRectMake(0, 0, 20, 20);
        [deleteBtn setBackgroundImage:[UIImage imageNamed:@"照片删除"] forState:UIControlStateNormal];
        deleteBtn.userInteractionEnabled = YES;
        [deleteBtn addTarget:self action:@selector(_deleteAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.layer.cornerRadius = 3.0;
        
        return cell;
        
    }
    
}

// 单元格选中事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == _imgAry.count) {
        
        [self addPicture]; // 添加图片
        
    } else {
        
        ByBigImageViewController *vc = [[ByBigImageViewController alloc] init];
        
        NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1];
        
        for (id item in _imgAry) {
            if ([item isKindOfClass:[ALAsset class]]) {
                UIImage *fullImage = [UIImage imageWithCGImage:[(ALAsset *)item defaultRepresentation].fullScreenImage];
                [tempArray addObject:fullImage];
            } else {
                [tempArray addObject:(UIImage *)item];
            }
            
        }
        vc.isLocal = YES;
        vc.imageData = tempArray;
        NSInteger index = indexPath.row;
        vc.indexPath = [NSIndexPath indexPathForItem:index inSection:0];
        [self.viewController presentViewController:vc animated:YES completion:nil];
    }
}
// 删除图片
- (void)_deleteAction:(UIButton *)button {
    
    // 找到对应的单元格来获得数组中图片的索引，然后删除图片，重载UICollectionView
    UICollectionViewCell *imgCell = (UICollectionViewCell *)button.superview;
    NSIndexPath *indexPath = [_collectionView indexPathForCell:imgCell];
    
    [_imgAry removeObjectAtIndex:indexPath.row];
    
    [_collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    [self fetchImgArray:_imgAry];
    
}


// 添加图片
- (void)addPicture {
    
    if (self.imgAry.count == 3) {
        [ByCoreToolAlert showOnlyText:@"您最多可上传3张图片"];
        return;
    }
    
    // 适配版本iOS8.0以上
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        
        NSString *albumButtonTitle = @"从相册中选择";
        NSString *cameraButtonTitle = @"拍照";
        NSString *cancelButtonTitle = @"取消";
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        // 添加点击动作
        // 取消
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:nil];
        // 相册中
        UIAlertAction *albumAction = [UIAlertAction actionWithTitle:albumButtonTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            
            [self _choosePhotoFromAlbum];
        }];
        // 拍照
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:cameraButtonTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self _getphotoFromCamera];
        }];
        
        
        [alertController addAction:cancelAction];
        [alertController addAction:albumAction];
        [alertController addAction:cameraAction];
        
        [self.viewController presentViewController:alertController animated:YES completion:nil];
    }
    // 适配版本8.0以下
    else {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册中选择",@"拍照", nil];
        [sheet showInView:self.viewController.view];
    }
}

#pragma mark - UIActionSheet代理方法（适配iOS8.0以下时使用）
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // 从相册中选择
    if (buttonIndex == 0) {
        [self _choosePhotoFromAlbum];
    }
    // 通过拍照获取
    else if (buttonIndex == 1) {
        [self _getphotoFromCamera];
    }
}

#pragma mark - 图片选择相关操作
// 从相册中选择照片
- (void)_choosePhotoFromAlbum {
    
    ByPhotoPickerViewController *picker = [[ByPhotoPickerViewController alloc] init];
    picker.delegate = self;
    picker.maxSelectedCount = 3 - self.imgAry.count;
    UINavigationController *root = [[UINavigationController alloc] initWithRootViewController:picker];
    [self.viewController presentViewController:root animated:YES completion:nil];
}
// 通过拍照获取照片
- (void)_getphotoFromCamera
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        [ByCoreToolAlert showOnlyText:@"相机不可用！"];
        return;
    }
    [self _changeToPickerController:sourceType];
}


#pragma mark - 照片多选回调
- (void)didSelectedAssets:(NSMutableArray *)assets {
    for (id item in assets) {
        if ([item isKindOfClass:[UIImage class]]) {
            [self.imgAry addObject:item];
        }else{
            UIImage *fullImage = [UIImage imageWithCGImage:[(ALAsset *)item defaultRepresentation].fullScreenImage];
            [self.imgAry addObject:fullImage];
        }
        [_collectionView reloadData];
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_imgAry.count inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        
    }
    // TODO: 上传多图
    [self fetchImgArray:self.imgAry];
}
- (void) fetchImgArray:(NSMutableArray *) array{
    if (self.addPhotoBlock) {
        self.addPhotoBlock(array);
    }
}
// 创建并跳转到图片获取界面
- (void)_changeToPickerController:(UIImagePickerControllerSourceType)sourceType {
    // 创建图片拾取界面
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    // 设置可编辑
    pickerController.sourceType = sourceType;
    if (pickerController.sourceType == UIImagePickerControllerSourceTypeCamera) {
        pickerController.allowsEditing = YES;
    }
    pickerController.title = @"图片选择";
    [pickerController.navigationBar setTintColor:[UIColor darkGrayColor]];
    [self.viewController presentViewController:pickerController animated:YES completion:nil];
}

// UIImagePickerController代理方法，选取图片之后处理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *showImage;
    UIImage *editedImage = (UIImage *)[info objectForKey:UIImagePickerControllerEditedImage];
    if (editedImage) {
        // 保存到相册
        UIImageWriteToSavedPhotosAlbum(editedImage, nil, nil, nil);
        // 设置图片
        showImage = editedImage; // 相册图片可截取，一直是正方形的
    }
    
    // 图片添加
    [self.imgAry addObject:showImage];
    [_collectionView reloadData];
    
    NSData *imageData = UIImageJPEGRepresentation(editedImage, 1);
    CGFloat length_kb = [imageData length] / 4096.0;
    // 压缩文件
    if (length_kb >= 500 ) {
        editedImage = [UIImage imageWithData:UIImageJPEGRepresentation(editedImage, 0)];
        imageData = UIImageJPEGRepresentation(editedImage, 1);
        length_kb = [imageData length] / 4096.0;
    }
    if (length_kb >= 500) {
        editedImage = [self scaleToSize:CGSizeMake(500, 500) :editedImage];
    }
    
    [self.viewController dismissViewControllerAnimated:YES completion:^{
        // TODO: 上传图片
        [self fetchImgArray:self.imgAry];
        
    }];
    
}


//裁剪图片
- (UIImage*)scaleToSize:(CGSize)size :(UIImage *)image {
    CGFloat width = CGImageGetWidth(image.CGImage);
    CGFloat height = CGImageGetHeight(image.CGImage);
    
    float verticalRadio = size.height*1.0/height;
    float horizontalRadio = size.width*1.0/width;
    
    float radio = 1;
    if(verticalRadio > 1 && horizontalRadio > 1)
    {
        radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;
    }
    else
    {
        radio = verticalRadio > horizontalRadio ? verticalRadio : horizontalRadio;
    }
    
    width = width*radio;
    height = height*radio;
    
    int xPos = (size.width - width)/2;
    int yPos = (size.height- height)/2;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(xPos, yPos, width, height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}

@end
